<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拼读卡片</title>
    <script src="xlsx.full.min.js"></script>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell;
            background: #f5f5f7;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 2rem;
        }

        .container {
            max-width: 800px;
            width: 100%;
        }

        .word {
            font-family: Arial;
            font-size: 72px;
            text-align: center;
            margin: 1rem 0;
            cursor: pointer;
        }

        .phonetic {
            font-family: 'Times New Roman';
            font-size: 32px;
            text-align: center;
            color: #666;
        }

        .meaning {
            font-family: '微软雅黑';
            font-size: 32px;
            text-align: center;
            margin: 1rem 0;
        }

        .syllable-container {
            background: #fff;
            border-radius: 20px;
            padding: 2rem;
            margin: 2rem 0;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .line {
            border-bottom: 2px solid #0071e3;
            height: 60px;
            margin: 1rem 0;
            position: relative;
        }

        .syllables {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            justify-content: center;
        }

        .syllable {
            background: #f5f5f7;
            border-radius: 10px;
            padding: 8px 16px;
            cursor: pointer;
            font-family: Arial;
            font-size: 36px;
            transition: all 0.3s;
        }

        button {
            background: #0071e3;
            color: white;
            border: none;
            padding: 12px 32px;
            border-radius: 25px;
            font-size: 20px;
            cursor: pointer;
            margin: 1rem auto;
            
            display: block;
        }

        .vowel {
            color: #ff3b30;
        }

        .consonant {
            color: #0071e3;
        }
        #practice-area{display: none;}
        .import-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #4CAF50;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 25px;
            cursor: pointer;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
            transition: all 0.3s;
            z-index: 100;
        }
        @keyframes shake {

            0%,
            100% {
                transform: translateX(0);
            }

            25% {
                transform: translateX(5px);
            }

            75% {
                transform: translateX(-5px);
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="syllable-container" id="read-area">
        <div class="word" onclick="toggleSyllables()">hello</div>
        <div class="phonetic">/həˈloʊ/</div>
        <div class="meaning">你好</div>
        <button onclick="practice()">Pratice</button>
    </div>
        <div class="syllable-container" id="practice-area">
            <div class="line syllables" id="dropZone"></div>
            <div class="syllables" id="syllablePool"></div>
            <button onclick="nextWord()">Next</button>
        </div>
        <input type="file" id="excelFile" accept=".xlsx" style="display: none;">
        
        <button class="import-btn" onclick="importExcel()">📁 Import Excel</button>

    </div>

    <script>
        const words = [
            { word: "hello", syllables: ["hel", "lo"], phonetic: "/həˈloʊ/", meaning: "你好" },
            { word: "world", syllables: ["wor", "ld"], phonetic: "/wɜːrld/", meaning: "世界" },
            { word: "apple", syllables: ["ap", "ple"], phonetic: "/ˈæpəl/", meaning: "苹果" },
            { word: "banana", syllables: ["ba", "na", "na"], phonetic: "/bəˈnænə/", meaning: "香蕉" },
            { word: "orange", syllables: ["or", "ange"], phonetic: "/ˈɔːrɪndʒ/", meaning: "橙子" },
            { word: "book", syllables: ["b", "oo", "k"], phonetic: "/bʊk/", meaning: "书" },
            { word: "computer", syllables: ["com", "pu", "ter"], phonetic: "/kəmˈpjuːtər/", meaning: "电脑" },
            { word: "phone", syllables: ["ph", "o", "ne"], phonetic: "/foʊn/", meaning: "电话" },
            { word: "table", syllables: ["ta", "ble"], phonetic: "/ˈteɪbəl/", meaning: "桌子" },
            { word: "chair", syllables: ["ch", "air"], phonetic: "/tʃer/", meaning: "椅子" }
        ];

        function practice() {
            document.getElementById('read-area').style.display = 'none';
            document.getElementById('practice-area').style.display = 'block';
            createSyllables(words[currentWordIndex].syllables);
        }

        function nextWord() {
            currentWordIndex = (currentWordIndex + 1) % words.length;
            isSplit = false;
            document.getElementById('dropZone').innerHTML = '';
            document.getElementById('practice-area').style.display = 'none';
            document.getElementById('read-area').style.display = 'block';
            updateDisplay();
        }

        // 添加 Excel 导入功能
        async function importExcel() {
            const input = document.getElementById('excelFile');
            input.click();
            
            input.onchange = async function(e) {
                const file = e.target.files[0];
                const reader = new FileReader();
                
                reader.onload = async function(e) {
                    const data = new Uint8Array(e.target.result);
                    const workbook = XLSX.read(data, {type: 'array'});
                    
                    // 获取第一个工作表
                    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                    
                    // 将工作表转换为JSON
                    const jsonData = XLSX.utils.sheet_to_json(firstSheet);
                    // 假设Excel的第一列是单词，第二列是音标，第三列是释义
                    jsonData.forEach(item => {
                        item.syllables = item.syllables.split(' - ');
                    });
                    
                    // 更新 words 数组
                    words.length = 0; // 清空原有数据
                    words.push(...jsonData);
                    
                    // 重置当前索引并更新显示
                    currentWordIndex = 0;
                    updateDisplay();
                };
                
                reader.readAsArrayBuffer(file);
            };
        }
        
        let currentWordIndex = 0;
        let isSplit = false;

        function updateDisplay () {
            const word = words[currentWordIndex];
            document.querySelector('.word').innerHTML = word.word;
            document.querySelector('.phonetic').textContent = word.phonetic;
            document.querySelector('.meaning').textContent = word.meaning;
            createSyllables(word.syllables);
        }

        function createSyllables (syllables) {
            const pool = document.getElementById('syllablePool');
            pool.innerHTML = '';
            syllables.sort(() => Math.random() - 0.5).forEach(syllable => {
                const div = document.createElement('div');
                div.className = 'syllable';
                div.textContent = syllable;
                div.addEventListener('click', () => moveSyllable(div));
                pool.appendChild(div);
            });
        }

        function moveSyllable (element) {
            const dropZone = document.getElementById('dropZone');
            if (element.parentElement === dropZone) {
                document.getElementById('syllablePool').appendChild(element);
            } else {
                dropZone.appendChild(element);
            }
            checkAnswer();
        }

        function checkAnswer() {
            const dropZone = document.getElementById('dropZone');
            const answer = [...dropZone.children].map(el => el.textContent).join('');
            if (answer === words[currentWordIndex].word) {
                showCorrectAnimation();
                playWordAudio(words[currentWordIndex].word);
            } else {
                // 如果是全部选择完了
                if (answer.length === words[currentWordIndex].word.length) {
                    
                // 播放错误音效 error.wav
                new Audio('error.wav').play().catch(e => console.log('播放失败:', e));
                
                // Add shake effect for incorrect answer
                dropZone.classList.add('shake');
                setTimeout(() => {
                    dropZone.classList.remove('shake');
                    // Reset syllables
                    updateDisplay();
                    // reset drop zone
                    document.getElementById('dropZone').innerHTML = '';
                }, 1500);
            }
            
            }
        }

        function showCorrectAnimation () {
            const wordEl = document.querySelector('.word');
            wordEl.style.transition = 'all 0.5s';
            wordEl.style.transform = 'scale(1.2)';
            setTimeout(() => {
                wordEl.style.transform = 'scale(1)';
                document.getElementById('syllablePool').innerHTML = '';
            }, 1000);
        }

        // 在toggleSyllables函数中添加播放逻辑
        function toggleSyllables () {
            const wordEl = document.querySelector('.word');
            if (!isSplit) {
                // 播放当前单词发音
                playWordAudio(words[currentWordIndex].word);

                wordEl.innerHTML = words[currentWordIndex].word.split('').map(letter =>
                    `<span class="${/[aeiou]/i.test(letter) ? 'vowel' : 'consonant'}">${letter}</span>`
                ).join('');
            } else {
                wordEl.innerHTML = words[currentWordIndex].word;
            }
            isSplit = !isSplit;
        }

        // 添加音频播放函数（需放在toggleSyllables之前）
        async function playWordAudio (word) {
            try {
                const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
                const data = await response.json();

                if (data && data[0]?.phonetics?.length) {
                    const audioUrl = data[0].phonetics.find(p => p.audio)?.audio;
                    if (audioUrl) {
                        new Audio(audioUrl).play().catch(e => console.log('播放失败:', e));
                    }
                }
            } catch (error) {
                console.error('获取音频失败:', error);
            }
        }

        function nextWord () {
            currentWordIndex = (currentWordIndex + 1) % words.length;
            isSplit = false;
            document.getElementById('dropZone').innerHTML = '';
            document.getElementById('read-area').style.display = 'block';
            document.getElementById('practice-area').style.display = 'none';

            updateDisplay();
        }

        updateDisplay();
    </script>
</body>

</html>